package com.etb.wisdom.eframe.dict.action;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.springframework.beans.factory.annotation.Autowired;

import com.etb.core.pojo.CriteriaType;
import com.etb.core.pojo.Page;
import com.etb.web.action.ETBAction;
import com.etb.web.eui.utils.EuiUtil;
import com.etb.wisdom.eframe.dict.service.EtbDicttypeService;
import com.etb.wisdom.eframe.dict.vo.DictTreeGridNode;
import com.etb.wisdom.eframe.model.EtbDicttype;

@Action("type")
@Namespace("/eframe/dict/type")
public class EtbDicttypeAction extends ETBAction<EtbDicttype> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1556470352874878653L;
	
	@Autowired
	private EtbDicttypeService typeService;

	@Override
	public String addView() {
		if(StringUtils.isNotBlank(id)) {
			EtbDicttype uplevelType = new EtbDicttype();
			uplevelType.setId(id);
			service.extend(uplevelType);
			request.setAttribute("uplevelType", uplevelType);
		}
		return ADD;
	}
	
	@Override
	public String updateView() {
		super.updateView();
		if(dataObject.getUplevelid() != null) {
			EtbDicttype uplevelType = new EtbDicttype();
			uplevelType.setId(dataObject.getUplevelid());
			service.extend(uplevelType);
			request.setAttribute("uplevelType", uplevelType);
		}
		return UPDATE;
	}
	
	@Override
	public void save() {
		typeService.save(dataObject);
	}

	@Override
	public void list() {
		if(page == null) page = new Page();
		if(criteria == null) criteria = new CriteriaType();
		criteria.setEntity(EtbDicttype.class.getName());
		
		if(id != null) {
			criteria.getExpr().clear();
			criteria.addExpr("uplevelid_eq", id);
		} else if(criteria.getExpr().size() == 0) {
			criteria.addExpr("uplevelid_eq", null);
		}
		
		page.init();
		List<DictTreeGridNode> treeData = new ArrayList<DictTreeGridNode>();
		List<EtbDicttype> types = service.query(criteria, page);
		for(EtbDicttype type: types) {
			DictTreeGridNode node = new DictTreeGridNode(type.getId(), type.getTypename(), type.getTypecode());
			if(id != null) {
				node.set_parentId(type.getUplevelid());
			}
			node.setState(DictTreeGridNode.State.closed.toString());
			treeData.add(node);
		}
		EuiUtil.toGrid(treeData, page);
	}
	
	public void getTypesByUplevelid() {
		EtbDicttype typeTemplate = new EtbDicttype();
		typeTemplate.setUplevelid(id);
		EuiUtil.toCombobox(service.query(typeTemplate));
	}

}